﻿var rate = $.cookie("PrimeGoldRate") || 1;
//var gem;
var orderID;
var scrollToph;
var  notbtn=""; //1有按钮
var app_url=location.origin;
var curstate = 0; //当前类别选项
var datalist = {};
    

(function(){
	OrderSearch();
	var order={
		init:function(){
			//导航栏的选中
            $('.wrapper').navbarscroll();
            $("#categories li").eq(2).addClass("cur").siblings().removeClass("cur");
			this.BindEvents();
		},
		BindEvents:function(){
			var self = this;
			if(APP){
				$("#order_term_btn").remove();
			}
            //筛选
            $("#order_term_btn").on("click", function () {
                if(APP){
                	var appJson={};
            		appJson.title="订单筛选";
            		appJson.url=app_url+"/Team/OrderFilter/?type=6";
            		YiYi_APP.showNewPage(JSON.stringify(appJson));
                }else{
                	location.href="/Team/OrderFilter/?type=6";
                }
            });
            $(".order-status span").on("click", function () { //订单状态选中
                $(this).addClass("active").siblings().removeClass("active");
            });
            //其他筛选条件点击添加样式、可多选
            $("#order_term_box").on("click", ".term span", function () {
                $(this).toggleClass("active");
            });
            $("#filter_product_btn").on("click", function () {
                $("#common_header").show();
                $("#order_term_btn").show();
                $("#order_term_box").hide();
                OrderSearch();
            });
			//点击全选
			$("#checkbox_check_all").on("click",function(){
				self.countCheck(0,0,0);//取消
				$(this).toggleClass("selected")
				if($(this).hasClass("selected")){
					$("#order .check_list_box").children("span").addClass("selected");
					$("#order .check_list_box span.selected").each(function (i, item) {
						var pre = parseFloat($(item).closest("li").find(".first").text());//当前点击行的每卡
    					var totalprice = parseFloat($(item).closest("li").find(".CurrentRMB .product_list_price").text());
    					var usd_totalprice = parseFloat($(item).closest("li").find(".CurrentUSD .product_list_price").text());
    					handleBtn();
						self.countCheck(1,pre,totalprice);
						self.countCheck(1,pre,usd_totalprice,"usd");
					});		
				}else{
					$(".check_list_box").children("span").removeClass("selected");
					clearAll();
					self.countCheck(0,0,0);//取消
				}
			});
			//列表的勾选框
			$("#order").on("click",".check_list_box",function(){
				$(this).children("span").toggleClass("selected");
				var pre = parseFloat($(this).closest("li").find(".first").text());//当前点击行的每卡
				var totalprice = parseFloat($(this).closest("li").find(".CurrentRMB .product_list_price").text());
				var usd_totalprice = parseFloat($(this).closest("li").find(".CurrentUSD .product_list_price").text());
				//判断是否全选
				var length=$("#order .check_list_box span.checkbox").length;
				var checkLength=$("#order .check_list_box span.selected").length;
				if(checkLength>0){
					handleBtn();
				}else{
					clearAll();
				}
				
				if(length==checkLength){
					$("#checkbox_check_all").addClass("selected");
				}else{
					$("#checkbox_check_all").removeClass("selected");
				}				
				if($(this).children("span").hasClass("selected")){
					self.countCheck(1,pre,totalprice);//选中
					self.countCheck(1,pre,usd_totalprice,"usd");//选中
				}else{
					self.countCheck(2,pre,totalprice);//取消
					self.countCheck(2,pre,usd_totalprice,"usd");//取消
				}
				
			});
			
			//采购订单输入验证 class=purchase_form
            var validate = $(".purchase_form").validate({
                debug: true, //调试模式取消submit的默认提交功能   
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应  
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form   
                    PurchaseOrder();//采购订单
                },
                rules: {
                    OriginSN: "required",
					Category: "required",
					Count: "required",
					Type: "required",
					AboutWeight: "required",
					CertType: "required",
					Material: "required",
					Series: "required",

                },
                messages: {
                    OriginSN: "",
					Category: "",
					Count: "",
					Type: "",
					AboutWeight: "",
					CertType: "",
					Material: "",
					Series: "",
                    
                }
            });

			//回裸钻库输入验证 class=_backdia
            var validate = $("._backdia").validate({
                debug: true, //调试模式取消submit的默认提交功能   
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应  
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form   
                    BackDia();//添加裸钻(回裸钻库)
                },
                rules: {                    
                    OriginSN: "required",
					Category: "required",
					Count: "required",
					Type: "required",
					AboutWeight: "required",
					CertType: "required",
					Material: "required",
					Series: "required",
					DeliveryTime: "required",
                    
                },
                messages: {
                    OriginSN: "",
					Category: "",
					Count: "",
					Type: "",
					AboutWeight: "",
					CertType: "",
					Material: "",
					Series: "",
					DeliveryTime: "",
                }
            });

		},

        //统计数据
        countCheck:function(type,pre,totalPrice,usd){			
			var price=parseFloat($("#check-total-price").text());
			var usd_price=parseFloat($("#check-total-price-usd").text());
			var pre_price=parseFloat($("#check-m-rmb").text());
			var _num = $(".check_list_box span.selected").length;;	
			if(type==1){//加				
				if(usd=="usd"){
					usd_price+=totalPrice
				}else{
					price+=totalPrice
					pre_price+=pre
				}
			}
			if(type==2){//减
				
				if(usd=="usd"){
					usd_price-=totalPrice
				}else{
					price-=totalPrice
					pre_price-=pre
				}
			}
			if(type==0){
				_num=0;
				price=0;
				usd_price=0;
				pre_price=0;
			}
			$("#check-num").text(_num);
			$("#check-m-rmb").text(formatRMBPrice(pre_price));
			$("#check-total-price").text(formatRMBPrice(price));
			$("#check-total-price-usd").text(formatUSDPrice(usd_price));
		},

		
	}
	order.init();
})();
        //绑定数据
        function BindingOrder(result) {
        	
            var _result = eval('(' + result + ')');//eval()解析单个json对象
            if (_result.msgcode == false) {//获取库存失败
                 $("#order_list").html('<div style="text-align:center;padding-top:20px;width:100%;">'+_result.msginfo+'</div>');
            } else { //获取库存成功
                _result = _result.msginfo.Data;
                var lis = "";//多行数据
                for (var i = 0; i < _result.length ; i++) {//_result.length
					var li = ""; //单行
					var data = _result[i];
                    lis += "<li>"+
                    "<div>"+
                    "<div class='check_list_box' lang='"+data.ReceiptStatus+"' data-customerID='"+data.CustomerID+"'>"+
                    "<span class='checkbox' name='checkbox' lang='" + data.OrderID + "' data='"+data.OrderStatus+"'></span></div>"+
                    "<div class='product_list' data-id="+data.OrderID +">"+
                    "<label class='product-parameter' data='"+data.Remarks+"' data-id='"+data.OrderID+"'  data-sn='"+data.OriginSN+"' data-pay='"+PaymentStatusFormat(_result[i].PaymentStatus)+"' lang='"+data.SalesExchangerate+"' style='display:none'></label>"+       
                    "<div class='list_img_box'>"+ShowImgOne(data)+"</div>"+
					"<div class='list_detail_box'>"+
					"<p>"+					
					"<b class='category' data='"+data.Category+"'>" + GetCategory("prime_golds",1) + "</b><b title='货号'>"+data.OriginSN+"</b>" +
					"<b class='type' data='" + _result[i].Type + "'>" + GetText("prime_golds", 1, data.Type, "Type") + "</b><b class='weight'>" + _result[i].Weight + "</b>" +
					"<b class='certType'>" + GetText("gems",data.Category,data.CertType,"CertType") + "</b><b class='category'>" + GetText("prime_golds", 1, data.Category, "Category") + "</b>" +
//                  "<b class='series'>" +_result[i].Series + "</b><b class='aboutWeight'>" + GetText("prime_golds", 1, data.AboutWeight, "AboutWeight") + "</b>"+
//                  "<b class='count'>" + data.Count + "</b><b class='material'>" + GetText("prime_golds", 1, data.Material, "Material") + "</b>"+
                    "<b class='place'>" + data.Country + data.State + "</b></p>"+
					"<div class='list_price' lang='"+formatRMBPrice(data.Price)+"'>￥<span class='product_list_price'>" + formatRMBPrice(data.Price) +
					"</span><span class='status_box' style='margin-left:10px'>"+ReceiptStatusFormat(data.ReceiptStatus)+"</span><span class='status_box' lang='"+data.OrderStatus+"'>"+UserOrderStatusFormat(data.OrderStatus)+"</span></div>"+
					"<div class='time_box'>下单日期：<span class='order-time'>"+DateTimeFormat(_result[i].AddTime)+"</span></div>"+
					"</div></div>"+modify_boxs(data)+
					"</li>";

					lis += li;//将单行加到多行
                }
                $("#order_list").html(lis);
                //   @*主题色start*@
			    $(document.createElement("script")).attr("src","/Js/ThemesColor.js").appendTo("html");
				//  @*主题色end*@
            }
        }
        
   
//自留回库 12-15 
function BackDia_Js(me,gwRate) {

    $.ajax({
        url: "/Team/GetPrimeGoldsOrderInfo",//提交地址
        type: "POST",//提交方式
        data: "{'OrderID':'" + me.getAttribute("value") + "'}",
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            var _result = eval('(' + result + ')');//eval()解析单个json对象
            if(_result.msgcode==true){
            _result = _result.msginfo;
            data = _result;
            myApp.popup(".BackDia_box");

            $("#_orID").val(_result.OrderID);//12-16
            $("#_invID").val(_result.ID);
            $("#originSN").val(_result.OriginSN);
			$("#category").val(_result.Category);
			$("#count").val(_result.Count);
			$("#type").val(_result.Type);
			$("#aboutWeight").val(_result.AboutWeight);
			$("#certType").val(_result.CertType);
			$("#material").val(_result.Material);
			$("#series").val(_result.Series);
			$("#country").val(_result.Country+_result.State);
			$("#supplier").val(_result.Supplier);
			$("#state").val(_result.State);
			$("#isStock").val(_result.IsStock);
			$("#weight").val(_result.Weight);
            
            $("#remark").val(_result.Remark);
            $("#onShelves").val(_result.OnShelves);

//          //原采购部分 01-12
            $("#back_purchaseExchange").val(_result.PurchaseExchangerate);//01-12采购汇率
            $("#sourceRMBGrain").val(Math.round(_result.PurchaseRMB)); //原人民币
            var back_purchaseRMBperCarat =Math.round((_result.PurchaseRMB / parseFloat($("#back_purchaseExchange").val())) / _result.Weight);
            $("#back_purchaseRMBperCarat").val((Math.round(_result.PurchaseRMB / _result.Weight))); //采购人民币每卡
            $("#sourceUSDPerGrain").val(Math.round(_result.PurchaseRMB / parseFloat($("#back_purchaseExchange").val())));//原美金
            $("#back_purchaseUSDPerCarat").val(Math.round(_result.PurchaseRMB / parseFloat($("#back_purchaseExchange").val()) / _result.Weight));//01-12  carat/usd采购美金每卡
        
//          //买
//          $("#buyUSDPerGrain").val(_result.PriceUSD);//01-12 买美金
//          $("#buyRMBGrain").val((_result.ConfirmPrice / (100 + _result.Confirmdiscount) * (100 + _result.DiscountReturn)).toFixed(2));//01-12买RMB

 			}else{
                $(".BackDia_box").hide();
                toast(_result.msginfo);     	
           	}

        }
    });
}    
        //回裸钻库12-16
        function BackDia(me){
            var requestDia = {};

            requestDia.OrderID = $("#_orID").val();//12-16
            requestDia.ID = $("#_invID").val();

            requestDia.OriginSN = $("#originSN").val();
            requestDia.Category = $("#category").val();
            requestDia.Count = $("#count").val();
            requestDia.Type = $("#type").val(); 
            requestDia.AboutWeight = $("#aboutWeight").val();
            requestDia.Material = $("#material").val();
            requestDia.Series = $("#series").val();
            requestDia.Country = $("#country").val();
            requestDia.Weight = $("#weight").val();
            requestDia.Measurement = $("#measurement").val();
            requestDia.Supplier = $("#supplier").val();  
 			requestDia.IsStock = $("#isStock").val();  
            requestDia.OnShelves = $("#onShelves").val();//上下架 12-28            
            requestDia.Comments = $("#remark").val();

//          原采购
			requestDia.PurchaseExchangerate = $("#back_purchaseExchange").val();//原采购汇率
//			requestDia.PurchaseRMBperCarat = $("#back_purchaseRMBperCarat").val();//原采购每卡￥
//			requestDia.PurchaseUSDPerCarat = (parseFloat($("#back_purchaseRMBperCarat").val()) / parseFloat($("#back_purchaseExchange").val())).toFixed(2); //$("#back_purchaseUSDPerCarat").val();//原采购每卡$
			requestDia.ConfirmPrice = (parseFloat($("#back_purchaseRMBperCarat").val()) *  parseFloat($("#weight").val())).toFixed(1); // $("#sourceRMBGrain").val(); //原采购总价￥
            requestDia.PurchaseUSDPerGrain = formatUSDPrice(Number($("#back_purchaseRMBperCarat").val()) *  Number($("#weight").val()) * Number($("#back_purchaseExchange").val()));   //$("#back_purchaseUSDPerGrain").val();//原采购总价$
            

//          //买
			requestDia.BuyUSDPerGrain = $("#buyUSDPerGrain").val();//买美金
			requestDia.BuyRMBGrain = $("#buyRMBGrain").val();//买人民币

            

            $.ajax({
                url: "/Team/PrimeGoldstockOrders",//提交地址
                type: "POST",//提交方式
                data: JSON.stringify(requestDia),
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var _result = eval('(' + result + ')');//eval()解析单个json对象

                    if (_result.msgcode == false) {
                        //添加失败(接口错误或程序内部错误)
                        myApp.alert("新增失败：" + _result.msginfo);
                    } else {
                        //添加成功
                        if (_result.result == true) {
                            //{\"count\": 1, \"ids_insert\": [5158997], \"ids\": [5158997], \"ids_update\": [], \"result\": true, \"count_update\": 0, \"count_insert\": 1}
                            myApp.alert("成功条目：" + _result.count + "\n\n新增条目：" + _result.count_insert + "\n\n更新条目：" + _result.count_update);
                            myApp.closeModal(".BackDia_box");//回库框关闭
                            OrderSearch();
                        } else {
                            //请求参数不符{\"msg\": \"\\u4ef7\\u683c\\u8f6c\\u6362\\u5931\\u8d25\", \"result\": false}
                            myApp.alert("新增失败：" + _result.msg);
                        }
                    }
                }
            });
        }
        //修改订单
        function modify_box(me) {
            $.ajax({
                url: "/Team/GetPrimeGoldsOrderInfo",//提交地址
                type: "POST",//提交方式
                data: "{'OrderID':'" + me.getAttribute("value") + "'}",
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var _result = eval('(' + result + ')');//eval()解析单个json对象
                	if(_result.msgcode==true){
	                _result = _result.msginfo;
	                myApp.popup(".modify_pop_box");
            
	            	$("#_orderID").val(_result.OrderID);
                    $("#_orderStat").val(_result.OrderStatus);//隐藏域11-3 
                    $("#_purOriginSN").val(_result.OriginSN);
                    $("#_purCategory").val(_result.Category);
                    
                    $("#_purCount").val(_result.Count);
                    $("#_purType").val(_result.Type);
                    $("#_purAboutWeight").val(_result.AboutWeight);//证书类型
                    $("#_purCertType").val(_result.CertType);
                    $("#_purMaterial").val(_result.Material);
		            $("#_purSeries").val(_result.Series);
		            $("#_purCountry").val(_result.Country+_result.State);
		            $("#_purWeight").val(_result.Weight);
		            
		            $("#_purSupplier").val(_result.Supplier);
		            $("#_purConfirmPrice").val(_result.ConfirmPrice);
		            $("#_purIsStock").val(_result.IsStock);
		              
                    $("#_purchaseExchange").val(_result.PurchaseExchangerate);  
                    $("#_PurchaseRemarks").val(_result.PurchaseRemarks);  
                    $("#_deliveryTime").val(DateTimeFormat(_result.ShipTime));
                    $("#_buyPriceUSD").val(formatUSDPrice(_result.PriceUSD)); //买美金
					$("#_buyPrice").val(formatRMBPrice(_result.PurchaseRMB)); //买人民币
	            }else{
	                $(".modify_pop_box").hide();
	                toast(_result.msginfo);
	            }
                    
                }
            });
        }
        
  		//采购订单8-20
        function PurchaseOrder(me) {  

            var requestOrder = {};
		
            requestOrder.OrderID = $("#_orderID").val();
            requestOrder.OrderStatus = $("#_orderStat").val();//11-3
            requestOrder.OriginSN = $("#_purOriginSN").val();//货号
            requestOrder.Category =$("#_purCategory").val();
            requestOrder.Count =$("#_purCount").val();
            requestOrder.AboutWeight =$("#_purAboutWeight").val();
            requestOrder.CertType =$("#_purCertType").val();
            requestOrder.Material =$("#_purMaterial").val();
            requestOrder.Series =$("#_purSeries").val();
            requestOrder.Country =$("#_purCountry").val();
            requestOrder.Weight = $("#_purWeight").val();
            requestOrder.Supplier =$("#_purSupplier").val();
            requestOrder.IsStock =$("#_purIsStock").val();
            requestOrder.ShipTime = $("#_deliveryTime").val();
            requestOrder.PurchaseRemarks = $("#_PurchaseRemarks").val();
            requestOrder.PurchaseExchangerate = $("#_purchaseExchange").val(); //采购汇率
            requestOrder.PurchaseRMB =  $("#_buyPrice").val();//买RMB
            requestOrder.PriceUSD = $("#_buyPriceUSD").val();;//买美金
            

            $.ajax({
                url: "/team/PrimeGoldsPurchaseOrder",//提交地址
                type: "POST",//提交方式
                data: JSON.stringify(requestOrder),
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var _result = eval('(' + result + ')');//eval()解析单个json对象
					myApp.alert(_result.msginfo);
                    myApp.closeModal(".modify_pop_box");//关闭采购订单框8-28
                    OrderSearch();//搜索订单8-28  
                }
            });
        }
        
        
   
